﻿package hapi.mvc;

import haxe.io.Bytes;
#if neko
import neko.io.File;
import neko.Utf8;
#elseif php
import php.io.File;
import php.Utf8;
#end
import hapi.mvc.TemplateProvider;

class FileTemplateProvider implements TemplateProvider {

	var baseDir:String;
	var extension:String;
	var skipBOM:Bool;
	
	public function new(?baseDir=".", ?extension="html", ?skipBOM=true) {
		this.baseDir = baseDir;
		this.extension = extension;
		this.skipBOM = skipBOM;
	}
	
	public function get(name):TemplateType {
		var str = readContent(baseDir + "/" + name + "." + extension);
		return new HapiTemplate(str);
	}
	
	function readContent(filePath):String {
		var bytes = File.getBytes(filePath);
		if (skipBOM && containsBOM(bytes)) {
			return bytes.toString().substr(3);
		}else {
			return bytes.toString();
		}
	}
	
	function containsBOM(bytes:Bytes) {
		return bytes.get(0) == 0xef && bytes.get(1) == 0xbb && bytes.get(2) == 0xbf;
	}
}